package com.ojoin.ojoin.eb_spider.service.catchdata;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.ojoin.ojoin.eb_spider.domain.BankCardCheck;
import com.ojoin.ojoin.eb_spider.service.SupplyInventoryService;
import com.ojoin.ojoin.eb_spider.service.SupplyPaymentService;
import com.ojoin.ojoin.eb_spider.service.WebDriverService;
import com.ojoin.ojoin.eb_spider.service.impl.SLDataCatchBaseServiceImpl;
import com.ojoin.trade.common.exception.BusinessException;
import com.ojoin.trade.common.utils.CommonUtils;
import com.ojoin.trade.common.utils.DownloadUtils;
import com.ojoin.trade.common.utils.LogUtils;
import com.ojoin.trade.common.utils.NumberUtils;
import com.ojoin.trade.common.utils.TimeUtils;
import com.ojoin.trade.common.utils.WaitUtil;
import com.ojoin.trade.common.utils.excel.ExcelReaderUtil;
import com.ojoin.trade.common.utils.excel.IRowReader;
import com.ojoin.trade.supplyloan_core.web.domain.CatchDataStartMessage;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlSupplyInventory;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlSupplyPayment;

/**
 * 天猫超市供应商 1.昨日库存 2.结算对账单
 */
@Service
public class SupplierTMALLDataCatchServiceImpl extends
		SLDataCatchBaseServiceImpl {

	private final String homeUrl = "http://scm.cbbs.tmall.com/user/index.htm#home/mywork";

	@Autowired
	private SupplyPaymentService paymentService;

	@Autowired
	private SupplyInventoryService inventoryService;
	private static Logger log = LoggerFactory
			.getLogger(SupplierTMALLDataCatchServiceImpl.class);

	@Override
	public void getBusinessData() throws Exception {
		try {
			getInstoreOrderData();
		} catch (BusinessException e){
			throw e;
		}catch (Exception e) {
			LogUtils.error(log, e);
			throw new BusinessException("抓取入库单数据出错");
		}

		try {
			getOutstoreOrderData();
		} catch (BusinessException e){
			throw e;
		}catch (Exception e) {
			LogUtils.error(log, e);
			throw new BusinessException("抓取出库单数据出错");
		}

		try {
			getUnpayAccountData();
		}catch (BusinessException e){
			throw e;
		} catch (Exception e) {
			LogUtils.error(log, e);
			throw new BusinessException("抓取结算单数据出错");
		}

		try {
			getUnpayAccountDatanow();
		} catch (BusinessException e){
			throw e;
		}catch (Exception e) {
			LogUtils.error(log, e);
			throw new BusinessException("抓取待结算未开票数据出错");
		}

		try {
			getPayAccountData();
		} catch (BusinessException e){
			throw e;
		}catch (Exception e) {
			LogUtils.error(log, e);
			throw new BusinessException("抓取付款单数据出错");
		}

		try {
			getFinancing();
		} catch (BusinessException e){
			throw e;
		}catch (Exception e) {
			LogUtils.error(log, e);
			throw new BusinessException("抓取融资记录据出错");
		}
		
	}

	public void initLogin(String baseUrl, String username, String password)
			throws BusinessException {

		this.getWebDriver().click("css", "a.login-tb");
		this.getWebDriver()
				.getWebDriverWait(10)
				.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By
						.id("J_loginIframe")));

		this.getWebDriver().sendKeys("id", "TPL_username_1", username);
		this.getWebDriver().sendKeys("id", "TPL_password_1", password);

		this.getWebDriver().click("id", "J_SubmitStatic");

	}

	@Override
	public boolean LoginByUserInfo(String baseUrl, String username,
			String password) throws BusinessException {

		String loginWay =  this.getAssistCatchData().getStartMess().getPlatformUser().getLoginWay();
		String loginReturnMess = "";

		this.getWebDriver().get(baseUrl);

		if ("taobao".equals(loginWay)) {
			// if (null != web) {

			initLogin(baseUrl, username, password);

			boolean loginFlag = this.getWebDriver().getWebDriverWait(60)
					.until(new ExpectedCondition<Boolean>() {
						public Boolean apply(WebDriver d) {
							return d.getTitle().equals("天猫B2C后台");
						}
					}).booleanValue();

			if (loginFlag) {
				return true;
			}

			try {

				loginReturnMess = this.getWebDriver().getText("css",
						"#J_Message > p");
				if ("为了你的账户安全，请拖动滑块完成验证".trim().equals(loginReturnMess.trim())) {
					// 验证码出错，继续登陆
					initLogin(baseUrl, username, password);

				} else if ("您输入的账户名与密码不匹配，请重新输入！".trim().equals(
						loginReturnMess.trim())) {

					LogUtils.info(log,  this.getAssistCatchData().getStartMess().getPlatformUser()
							.getPlatformName()
							+ "-->username"
							+ username
							+ "登陆失败-->输入的账户名与密码不匹配%s");

				}

				this.getWebDriver().switchToDefaultContent();
				if (this.getWebDriver()
						.findElements("className", "aq_def_overlay").size() != 0) {
					this.getWebDriver().getWebDriverWait(60)
							.until(new ExpectedCondition<Boolean>() {
								public Boolean apply(WebDriver d) {
									return d.getTitle().equals("登录页面");
								}
							});
				}

				WaitUtil.waitTimeSeconds(3);
				// force redirect
				this.getWebDriver().get(homeUrl);

			} catch (Exception e) {
				// 异常可忽略
				LogUtils.info(log,  this.getAssistCatchData().getStartMess().getPlatformUser()
						.getPlatformName()
						+ "-->username" + username + "登陆-->出现验证码%s");

			}

			// / }
			// double validate

		} else {
			WebElement loginname = this.getWebDriver().findElement("id",
					"login-name");
			WebElement nloginpwd = this.getWebDriver().findElement("id",
					"pass-word");

			loginname.sendKeys(username);
			nloginpwd.sendKeys(password);
		}

		return false;
	}

	@Override
	public String catchSupplierName() throws BusinessException {
		return this.getWebDriver().findElement("css", ".lp4-log-user")
				.getText().trim();
	}

	@Override
	public BankCardCheck catchSupplierAccount() throws BusinessException {
		// 确保首页真正加载(跳过介绍)
		 BankCardCheck bcc = new BankCardCheck();
		this.getWebDriver().findElement("id", "menu-item-next_mywork").click();

		this.getWebDriver()
				.getWebDriverWait(10)
				.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By
						.cssSelector("iframe[src*='myWork.htm']")));

		this.getWebDriver()
				.findElement("css", "a[data-id='scmPersonalInfoUrl']").click();

		this.getWebDriver().switchToDefaultContent();

		this.getWebDriver()
				.getWebDriverWait(10)
				.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By
						.cssSelector("iframe[src*='view_supplier_detail.htm']")));

		String account = this
				.getWebDriver()
				.findElement("xpath", "/html/body/div/div[5]/div[1]/div[2]/div")
				.getText();
		if (StringUtils.isEmpty(account)) {
			String aliAccount = this
					.getWebDriver()
					.findElement("xpath",
							"/html/body/div/div[5]/div[3]/div[2]/div")
					.getText();
			account = aliAccount;
		}

		bcc.setBankNum(account);
		return bcc;
	}

	@Override
	public boolean getInstoreOrderData() throws IOException {
		// final List<Double> currTotalCost = new ArrayList<Double>();
		// 未付款结算库存单
		final List<TbSlSupplyInventory> invs = new ArrayList<TbSlSupplyInventory>();
		// 实时库存(找到供应商ID)
		String realtimeInv = "http://scm.cbbs.tmall.com/user/index.htm#report/realtimeInventory";
		this.getWebDriver().get(realtimeInv);

		this.getWebDriver()
				.getWebDriverWait(10)
				.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By
						.cssSelector("iframe[src*='smRealtimeInventoryListV2.htm']")));

		String TmallSupplierID = this.getWebDriver()
				.findElement("css", "#searchForm input[name='supplierId']")
				.getAttribute("value");

		this.getAssistCatchData().getContext().put("TmallSupplierID", TmallSupplierID);

		LogUtils.info(log, "实时库存(找到供应商ID) {}-->TmallSupplierID"
				+ TmallSupplierID);

		if (!CommonUtils.isEmpty(TmallSupplierID)) {
			String curDate = TimeUtils.getYesterdayDate();
			String yestdayInvRepDownloadUrl = "http://scm.cbbs.tmall.com/biSyncInvPageExport.htm?type=biInvReport&itemStatus=0&selfStatus=-1&startTime="
					+ curDate
					+ "&endTime="
					+ curDate
					+ "&supplierCode="
					+ TmallSupplierID;

			File downloadFileDir = new File( this.getAssistCatchData().getDownloadDir());

			this.getWebDriver().get(yestdayInvRepDownloadUrl);
			// webDriver.getDriver().getp
			IRowReader reader = new IRowReader() {
				private Set<String> ids = new HashSet<String>();

				public void getRows(int sheetIndex, String sheetName,
						int curRow, List<String> rowlist) {
					// ignore header

					if (rowlist.size() != 48) {
						throw new BusinessException("invReport文件格式出错，不是48行");
					}

					if (0 == curRow) {
						return;
					}
					// 总库存金额

					String warehouse = rowlist.get(2);
					String productNum = rowlist.get(6);

					String key = warehouse + "_" + productNum;

					if (ids.contains(key)) {
						LogUtils.info(log, "{%s}天猫库存表记录重复", key);
						return;

						// throw new BusinessException("天猫库存表记录重复");
					} else {
						ids.add(key);
					}

					String totalAmount = rowlist.get(25);
					if (!"0.0".equals(totalAmount) && !"0".equals(totalAmount)
							&& !CommonUtils.isEmpty(totalAmount)) {

						String createDateTime = rowlist.get(0);

						String fm = "yyyyMMdd";

						DateTimeFormatter format = DateTimeFormat
								.forPattern(fm);
						DateTime dtcreate = DateTime.parse(createDateTime,
								format);

						TbSlSupplyInventory inventory = new TbSlSupplyInventory();
						inventory
								.setPlatformAccountId(SupplierTMALLDataCatchServiceImpl.this.getAssistCatchData()
										.getStartMess().getPlatformUser()
										.getId());
						inventory.setItemId(rowlist.get(3));
						inventory.setStoreDate(dtcreate.toString("yyyy-MM-dd"));
						inventory.setItemStatus(TbSlSupplyInventory.IN);
						inventory.setItemKey(key);
						// double amountD = Double.valueOf(totalAmount) * 100;

						long amountD = NumberUtils.getLongAmount(totalAmount);

						// currTotalCost.add(amountD);
						inventory.setTotalCost(amountD);

						invs.add(inventory);
					}
				}
			};

			FileInputStream in = null;
			File invReport = null;
			try {
				invReport = DownloadUtils.waitFileDownloadOver(downloadFileDir,
						"^invR.*.csv$");

				LogUtils.info(log, "库存文件" + invReport.getAbsolutePath());

				in = new FileInputStream(invReport);
				ExcelReaderUtil.readCSV(reader, in, "GBK");

				// 每天都是全量，不需要过滤
				 this.getAssistCatchData().getCata().setInstore(invs);
			} catch (Exception e) {
				LogUtils.error(log, e);
				throw new BusinessException("解析invReport文件失败 ");
			} finally {
				IOUtils.closeQuietly(in);

			}
		}

		return true;
	}

	/**
	 * <option value="10">待商家审核</option> <option value="15">结算人员已驳回</option>
	 * <option value="20">待结算人员审核</option> <option value="21">被合并的结算单</option>
	 * <option value="25">财务已驳回</option> <option value="30">待财务审核</option>
	 * <option value="35">出纳已驳回</option> <option value="40">待执行打款</option>
	 * 
	 * @throws IOException
	 */

	@Override
	public boolean getUnpayAccountData() throws BusinessException, IOException {
		// 获取所有结算单
		/*
		 * Map<String, TbSlSupplyPayment> waitpay = getPaymentService()
		 * .queryByUidAndsettlementState(getPlatformUser().getId(),
		 * TbSlSupplyPayment.WAITPAY);
		 */

		// 对账单
		final List<String> keepStatus = new ArrayList<String>();

		keepStatus.add("待商家审核");
		keepStatus.add("结算人员已驳回");
		keepStatus.add("待结算人员审核");
		keepStatus.add("被合并的结算单");
		keepStatus.add("财务已驳回");
		keepStatus.add("待财务审核");
		keepStatus.add("出纳已驳回");
		keepStatus.add("待执行打款");

		String tmallSupplierID = String.valueOf( this.getAssistCatchData().getContext().get(
				"TmallSupplierID"));
		String downloadPaymentExcelUrl = "http://scm.cbbs.tmall.com/exportExcel.do?type=activePaymentInfo&sellerId=0&infoId=&settleStatus=0&storeCode=&operator=&operatorTime=&gmtCreate=&supplierCode="
				+ tmallSupplierID;

		File downloadFileDir = new File( this.getAssistCatchData().getDownloadDir());

		this.getWebDriver().get(downloadPaymentExcelUrl);

		final List<TbSlSupplyPayment> payments = new ArrayList<TbSlSupplyPayment>();

		IRowReader reader = new IRowReader() {

			public void getRows(int sheetIndex, String sheetName, int curRow,
					List<String> rowlist) {

				if (rowlist.size() != 18) {
					throw new BusinessException("payment文件格式出错，不是18行");
				}

				if (0 == curRow) {
					return;
				}

				String status = rowlist.get(12);
				String tid = rowlist.get(0);
				LogUtils.info(SupplierTMALLDataCatchServiceImpl.log, "tid-->"
						+ tid + "---状态-->" + status);

				
				String createDateTime = rowlist.get(15).substring(0,10);
				
				
				String stramount = rowlist.get(11);
			
				TbSlSupplyPayment payment = new TbSlSupplyPayment();
				payment.setPlatformAccountId(SupplierTMALLDataCatchServiceImpl. this.getAssistCatchData()
						.getStartMess().getPlatformUser().getId());
				payment.setSettlementId(String.valueOf(tid));

				try {
					if (TimeUtils.getDateSpaceOfDay(createDateTime,
							SupplierTMALLDataCatchServiceImpl. this.getAssistCatchData()
									.getStartMess().getSettlementStartTime()) < 0) {
						SupplierTMALLDataCatchServiceImpl. this.getAssistCatchData().getStartMess()
								.setSettlementStartTime(createDateTime);
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				if (!keepStatus.contains(status)) {
					payment.setSettlementState(TbSlSupplyPayment.COMPLETEPAY);
					String updateDateTime = rowlist.get(14).substring(0,10);
					
					payment.setPayDate(updateDateTime);
				} else {
					payment.setSettlementState(TbSlSupplyPayment.WAITPAY);
				}
				payment.setCreateDate(createDateTime);
				payment.setSettlementDate(createDateTime);
				long amountD = NumberUtils.getLongAmount(stramount);

				payment.setAmount(amountD);
				payments.add(payment);

			}
		};

		FileInputStream in = null;
		File payment = null;
		try {
			payment = DownloadUtils.waitFileDownloadOver(downloadFileDir,
					"^payment-info.*.xlsx$");

			LogUtils.info(log, "文件名为：" + payment.getAbsolutePath() + "-->文件大小："
					+ payment.length() / 1024 + "kb");

			in = new FileInputStream(payment);

			ExcelReaderUtil.readExcel(reader, in);

			 this.getAssistCatchData().getCata().setSettlement(payments);

			LogUtils.info(log,
					"getUnpayAccountData--payments：" + payments.size()
							+ "-->执行完毕");

		} catch (Exception e) {
			LogUtils.error(log, e);
			throw new BusinessException("解析payment文件失败");
		} finally {
			IOUtils.closeQuietly(in);
		}

		return true;
	}

	public boolean getUnpayAccountDatanow() throws Exception {

		final List<TbSlSupplyPayment> payments = new ArrayList<TbSlSupplyPayment>();
		// final Set<String> set = new HashSet<String>();
		String tmallSupplierID = String.valueOf( this.getAssistCatchData().getContext().get(
				"TmallSupplierID"));

		final int[] clearingsDay = { 1, 11, 21 };

		String time = TimeUtils.getCurDate();
		String needtime = TimeUtils.getLastBefore(clearingsDay, time);

		String SettlementS =  this.getAssistCatchData().getStartMess().getSettlementStartTime();

		if (TimeUtils.getDateSpaceOfDay(needtime, SettlementS) < 0) {
			// needtime = SettlementS;
			needtime = TimeUtils.getLastBefore(clearingsDay, SettlementS);
		}

		String downloadPaymentExcelUrl = "http://scm.cbbs.tmall.com/biSyncSuppPageExport.htm?type=biItemReportSupp&startTime="
				+ needtime
				+ "&endTime="
				+ time
				+ "&cate1=&cate2=&cate3=&cate4=&brandName=&itemId=&itemTitle=&storeCode=&supplierCode="
				+ tmallSupplierID;

		File downloadFileDir = new File( this.getAssistCatchData().getDownloadDir());

		this.getWebDriver().get(downloadPaymentExcelUrl);

		IRowReader reader = new IRowReader() {

			public void getRows(int sheetIndex, String sheetName, int curRow,
					List<String> rowlist) {

				if (rowlist.size() != 20) {
					throw new BusinessException("suppReport文件格式出错，不是20行");
				}

				if (0 == curRow) {
					return;
				}

				String tid = rowlist.get(2);
				String bid = rowlist.get(9);
				String key = tid + "_" + bid;
				/*
				 * if(set.contains(key)){ return ; }else { set.add(key); }
				 */
				String fm = "yyyyMMdd";
				String createDateTime = rowlist.get(0);
				DateTimeFormatter format = DateTimeFormat.forPattern(fm);

				DateTime dtcreate = DateTime.parse(createDateTime, format);
				String time = dtcreate.toString("yyyy-MM-dd");

				String stramount = rowlist.get(14);

				TbSlSupplyPayment payment = new TbSlSupplyPayment();
				payment.setPlatformAccountId(SupplierTMALLDataCatchServiceImpl. this.getAssistCatchData()
						.getStartMess().getPlatformUser().getId());
				payment.setSettlementId(key);

				payment.setSettlementState(TbSlSupplyPayment.CHECKEDPAY);
				payment.setCreateDate(time);
				long amountD = NumberUtils.getLongAmount(stramount);

				payment.setAmount(amountD);
				payments.add(payment);

			}
		};

		FileInputStream in = null;
		File payment = null;
		try {
			payment = DownloadUtils.waitFileDownloadOver(downloadFileDir,
					"^suppReport.csv$");

			LogUtils.info(log, "文件名为：" + payment.getAbsolutePath() + "-->文件大小："
					+ payment.length() / 1024 + "kb");

			in = new FileInputStream(payment);

			ExcelReaderUtil.readCSV(reader, in, "GBK");

			 this.getAssistCatchData().getCata().setSettlementcheck(payments);

			LogUtils.info(log,
					"getUnpayAccountData--payments：" + payments.size()
							+ "-->执行完毕");

		} catch (Exception e) {
			LogUtils.error(log, e);
			throw new BusinessException("解析payment文件失败");
		} finally {
			IOUtils.closeQuietly(in);
		}

		return true;
	}

	@Override
	public boolean getPayAccountData() throws BusinessException {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public boolean getOutstoreOrderData() throws BusinessException {
		// TODO Auto-generated method stub
		return true;
	}
	
	public boolean getFinancing(){
		//String url = "http://scm.cbbs.tmall.com/user/index.htm#financing/financingList";
		String url = "http://supplier.cbbs.tmall.com/supplier/news/financingList.htm";
		this.getWebDriver().getAndPageLoad(url);
		 
		//this.getWebDriver().switchToframe(this.getWebDriver().findElement("css", "#J_TabConId_financingList > iframe"));
		
		List<TbSlSupplyPayment> financing = new ArrayList<TbSlSupplyPayment>();
		List<WebElement> list = this.getWebDriver().findElements("css", "#grid > div > div.bui-grid-body > table tr");
		if(!CommonUtils.isEmpty(list)){
			Iterator<WebElement> it = list.iterator();
			while(it.hasNext()){
				WebElement tr = it.next();
				if(!tr.getAttribute("class").equals("bui-grid-header-row")){
					List<WebElement> tds = this.getWebDriver().findElements(tr, WebDriverService.tagName, "td");
					if(!CommonUtils.isEmpty(tds)){
						
						String balance = this.getWebDriver().findElement( tds.get(7),"css", "div > span").getText();
						
						if(CommonUtils.isEmpty(balance)){
							break ;
						}
						
						String itemId = this.getWebDriver().findElement( tds.get(0),"css", "div > span").getText();
						String time = this.getWebDriver().findElement( tds.get(3),"css", "div > span").getText();
						String stramount = this.getWebDriver().findElement( tds.get(5),"css", "div > span").getText();
						
						TbSlSupplyPayment payment = new TbSlSupplyPayment();
						payment.setPlatformAccountId(SupplierTMALLDataCatchServiceImpl. this.getAssistCatchData()
								.getStartMess().getPlatformUser().getId());
						payment.setSettlementId(itemId);

						payment.setSettlementState(TbSlSupplyPayment.FINANCING);
						payment.setCreateDate(time);
						long amountD = NumberUtils.getLongAmount(stramount);

						payment.setAmount(amountD);
						financing.add(payment);
						
					}
				}
				 
			}
		}
		
		 this.getAssistCatchData().getCata().setFinancing(financing);
		return true ;
	};
	
	@Override
	public BankCardCheck isSupplyAccountCorrect() throws BusinessException {
		BankCardCheck bcc = new BankCardCheck();
		bcc.setCorrect(true);
		
		return bcc;
	}
	
	// TODO　不保存
	@Override
	public void saveCookies() throws IOException {
		
	}
	
}
